﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using GameFramework.ObjectPool;
using System.Collections.Generic;
using UnityEngine;
using UnityGameFramework.Runtime;


namespace Adventure
{
    public class MonoPoolComponent : GameFrameworkComponent //(先注册在框架里，也可以直接继承Mono)
    {
        [SerializeField] protected string m_ItemName = null;
        //复用预制体
        [SerializeField] private MonoPoolItem m_ItemTemplate = null;
        //父节点
        [SerializeField] private Transform m_InstanceRoot = null;
        //对象池容量
        [SerializeField] private int m_InstancePoolCapacity = 5;
        //对象池
        private IObjectPool<MonoPoolObject> m_ItemObjectPool = null;
        public virtual void Start()
        {
            Init(m_ItemName);
        }

        //初始化对象池
        public void Init(string name/*, MonoPoolItem templete, Transform room, int capacity*/)
        {
            //m_ItemTemplate = templete;
            //m_InstanceRoot = room;
            //m_InstancePoolCapacity = capacity;

            m_ItemObjectPool =
                GameEntry.ObjectPool.CreateSingleSpawnObjectPool<MonoPoolObject>(name, m_InstancePoolCapacity);
        }

        //创建Item
        public MonoPoolItem ShowItem(object data)
        {
            var item = GenItem();
            item.Init(data);
            return item;
        }

        //回收Item
        public void HideItem(MonoPoolItem item)
        {
            item.Reset();
            m_ItemObjectPool.Unspawn(item);
        }

        //生成或复用Item
        private MonoPoolItem GenItem()
        {
            MonoPoolItem cellItem = null;
            MonoPoolObject cellItemObject = m_ItemObjectPool.Spawn();
            if (cellItemObject != null)
            {
                cellItem = (MonoPoolItem)cellItemObject.Target;
            }
            else
            {
                cellItem = Instantiate(m_ItemTemplate);
                Transform transf = cellItem.GetComponent<Transform>();
                transf.SetParent(m_InstanceRoot);
                transf.localScale = Vector3.one;
                m_ItemObjectPool.Register(MonoPoolObject.Create(cellItem), true);
            }

            cellItem.gameObject.SetActive(true);
            return cellItem;
        }
    }
}
